﻿/* Copyright (C) 2007-2010 STS Soft

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

using System;
using System.IO;
using System.Collections.Generic;
using STSdb.General.Collections;
using STSdb.General.Compression;
using STSdb.General.Buffers;

namespace STSdb.Persist
{
    public class ByteArrayIndexerPersist : IIndexerPersist<Byte[]>
    {
        #region IIndexerPersist<Byte[]> Members

        public void Store(BinaryWriter writer, IIndexer<Byte[]> values)
        {
            byte[] buffer = new byte[(int)Math.Ceiling(values.Count / 8.0)];

            byte[][] array = new byte[values.Count][];
            int length = 0;

            for (int i = 0; i < values.Count; i++)
            {
                byte[] value = values[i];

                if (value != null)
                {
                    buffer.SetBit(i, 1);
                    array[length++] = value;
                }
                //else
                //    buffer.SetBit(i, 0);
            }

            writer.Write(buffer);

            for (int i = 0; i < length; i++)
            {
                byte[] value = array[i];
                CountCompression.Serialize(writer, value.Length);
                writer.Write(value);
            }
        }

        public void Load(BinaryReader reader, IIndexer<Byte[]> values)
        {
            byte[] buffer = reader.ReadBytes((int)Math.Ceiling(values.Count / 8.0));

            for (int i = 0; i < values.Count; i++)
            {
                if (buffer.GetBit(i) == 1)
                {
                    int length = (int)CountCompression.Deserialize(reader);
                    values[i] = reader.ReadBytes(length);
                }
                else
                    values[i] = null;
            }
        }

        #endregion
    }
}
